const errorType = require('../constants/error_types')
const service = require('../service/user_service')
const md5password = require('../utils/password_handle')

// 注册的逻辑
const verifyUser = async (ctx,next)=>{
  // 获取用户名和密码
  const {name,password} = ctx.request.body

  // 判断是否为空
  if(!name || !password){
    const error = new Error(errorType.NAME_OR_PASSWORD_IS_EMP)
    return ctx.app.emit('error',error,ctx)
  }

  // 判断用户名是否已被注册
  const result = await service.getUserByName(name)
  if(result.length){
    const error = new Error(errorType.NAME_ALREADY_EXIST)
    return ctx.app.emit('error',error,ctx)
  }

  await next()
}

// 密码加密
const handlePassword = async(ctx,next)=>{
  const {password} = ctx.request.body
  ctx.request.body.password = md5password(password)

  await next()
}

module.exports = {
  verifyUser,
  handlePassword
}